from ability.enums import ErrorCode
from rest_framework import mixins, viewsets
from ability.serializer.course import ChapterCreateSerializer, CourseStudentsSerializer
import traceback
from django.db.models.query_utils import Q
from ability.format import CustomResponse, GetPostParaOrNone
from ability.models import Chapter, Course
from ability.serializer.serializers import ChapterSerializer
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from rest_framework.views import APIView
from ability.excepts import LogicException
import ability.permissions as pm
from rest_framework import permissions

class ChapterAddView(APIView):

    permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission|pm.TeacherPermission]
    def __init__(self, **kwargs):
        self.response_format = CustomResponse().response
        self.message = ""
        super(ChapterAddView, self).__init__(**kwargs)

    def check_chapter(self, chapter_id, course_id):
        try:
            chapter = Chapter.objects.get(Q(id = None if chapter_id == '' else chapter_id), Q(course__id = course_id))
            return chapter
        except Chapter.DoesNotExist:
            return None

    def check_course(self, obj_id):
        try:
            course = Course.objects.get(id = obj_id, teacher=self.request.user.teacher) if self.request.user.user_type == 'T' else Course.objects.get(id = obj_id)
            return course
        except Course.DoesNotExist:
            return None

    def post(self, request, *args, **kwargs):
        try:
            serializer = ChapterCreateSerializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            course = self.check_course(serializer.validated_data['course_id'])
            if course is None:
              raise LogicException('参数不正确')

            serializer.save()

            self.message = '章节创建成功\n'
            self.response_format["message"] = self.message
            self.response_format['data'] = serializer.data
            return Response(self.response_format)
        except LogicException as e: 
            self.response_format["message"] = str(e)
            self.response_format["error_code"] = -1 
            return Response(self.response_format)
        except Exception as e:
            traceback.print_exc()
            self.response_format["message"] = str(e)
            self.response_format["error_code"] = -1 
            return Response(self.response_format)

class CourseStudentListAPIView(ListAPIView):
    permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission|pm.TeacherPermission]
    serializer_class = CourseStudentsSerializer
    model = serializer_class.Meta.model
    def get_serializer_context(self):
        context = super(CourseStudentListAPIView, self).get_serializer_context()
        context.update({"course_id": self.kwargs['course_id']})
        return context
    def get_queryset(self):
        course_id = self.kwargs['course_id']
        queryset = self.model.objects.filter(Q(course__id=course_id)) if self.request.user.user_type == 'A' else self.model.objects.filter(Q(course__id=course_id),Q(course__teacher=self.request.user.teacher))
        return queryset

class ChapterOneViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    serializer_class = ChapterSerializer
    permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission|pm.TeacherPermission|pm.StudentPermission]

    def __init__(self, **kwargs):
        self.response_format = CustomResponse().response
        super(ChapterOneViewSet, self).__init__(**kwargs)
    
    def get_queryset(self):
        return Chapter.objects.filter(id = self.kwargs['pk'])

    def retrieve(self, request, chapter_id=None):
        queryset = Chapter.objects.all() if self.request.user.user_type == 'A' else Chapter.objects.filter(course__teacher=self.request.user.teacher) if self.request.user.user_type == 'T' else Chapter.objects.filter(course__student=self.request.user.student)
        try:
            one = queryset.get(id = self.kwargs['chapter_id'])
            serializer = ChapterSerializer(one)
            self.response_format["data"] = serializer.data
        except Chapter.DoesNotExist:
            self.response_format["error_code"] = ErrorCode.parameter_error.value
            self.response_format["message"] = '章节ID不存在'
        
        return Response(self.response_format)